import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../widgets/gradient_background.dart';
import '../widgets/app_button.dart';
import '../services/baidu_speech_service.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:async';

class VoiceDivinationPage extends StatefulWidget {
  const VoiceDivinationPage({Key? key}) : super(key: key);

  @override
  State<VoiceDivinationPage> createState() => _VoiceDivinationPageState();
}

class _VoiceDivinationPageState extends State<VoiceDivinationPage> with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _pulseAnimation;
  bool _isListening = false;
  String _recognizedText = '';
  final BaiduSpeechService _voiceService = BaiduSpeechService(
    apiKey: "C9NfG38p6l02zU5YbxSZkeKf",
    secretKey: "jnqPxyPtdYPgrsSQk5mwzMGAmApkPvBM",
  );
  bool _isInitialized = false;
  bool _permissionDenied = false;
  StreamSubscription? _textSubscription;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat(reverse: true);
    
    _pulseAnimation = Tween<double>(begin: 1.0, end: 1.05).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: Curves.easeInOut,
      ),
    );
    
    // 初始化语音服务
    _initializeVoiceService();
  }

  // 初始化语音服务
  Future<void> _initializeVoiceService() async {
    bool initialized = await _voiceService.initialize();
    setState(() {
      _isInitialized = initialized;
      _permissionDenied = !initialized;
    });
    
    // 订阅语音识别结果流
    _textSubscription = _voiceService.textStream.listen((text) {
      // 检查是否是错误信息
      if (text.startsWith('麦克风权限被永久拒绝') || text.startsWith('初始化语音服务失败')) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(text),
            backgroundColor: Colors.red,
          ),
        );
      }
      
      setState(() {
        _recognizedText = text;
      });
    });
  }

  // 切换录音状态
  Future<void> _toggleListening() async {
    if (!_isInitialized) {
      _showPermissionDialog();
      return;
    }
    
    if (!_isListening) {
      // 开始录音
      bool started = await _voiceService.startRecording();
      if (!started) {
        // 如果启动录音失败，显示错误信息
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('无法启动录音，请检查权限设置'),
            backgroundColor: Colors.red,
          ),
        );
        return;
      }
      
      setState(() {
        _isListening = started;
        if (started) {
          _recognizedText = '';
        }
      });
    } else {
      // 停止录音
      await _voiceService.stopRecording();
      setState(() {
        _isListening = false;
      });
      
      // 如果有识别结果，跳转到结果页面
      if (_recognizedText.isNotEmpty && !_recognizedText.startsWith('麦克风权限被永久拒绝') && !_recognizedText.startsWith('初始化语音服务失败')) {
        Future.delayed(const Duration(milliseconds: 500), () {
          Navigator.pushNamed(
            context,
            '/divination-result',
            arguments: {
              'text': _recognizedText,
              'type': 'voice',
            },
          );
        });
      }
    }
  }

  // 显示权限请求对话框
  void _showPermissionDialog() {
    String title = '需要权限';
    String content = '语音起卦功能需要麦克风权限，请在设置中允许访问麦克风。';
    
    // 根据错误类型显示不同的提示
    if (!_isInitialized && _recognizedText.startsWith('麦克风权限被永久拒绝')) {
      title = '权限被拒绝';
      content = '麦克风权限被永久拒绝，无法使用语音起卦功能。请在设置中允许麦克风权限。';
    } else if (!_isInitialized && _recognizedText.startsWith('初始化语音服务失败')) {
      title = '初始化失败';
      content = '语音服务初始化失败，请稍后重试或检查设备设置。';
    }
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          if (title == '需要权限' || title == '权限被拒绝')
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                openAppSettings();
              },
              child: const Text('去设置'),
            ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    _voiceService.dispose();
    _textSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GradientBackground(
        child: SafeArea(
          child: Column(
            children: [
              // 顶部栏
              Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 20,
                  vertical: 15,
                ),
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: () => Navigator.pop(context),
                      child: const Text(
                        '←',
                        style: TextStyle(
                          fontSize: 24,
                          color: Colors.black,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Center(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            SvgPicture.asset(
                              'assets/icons/app_logo.svg',
                              width: 28,
                              height: 28,
                            ),
                            const SizedBox(width: 8),
                            Text(
                              '语音起卦',
                              style: Theme.of(context).textTheme.displayMedium,
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(width: 24),
                  ],
                ),
              ),
              
              // 主体内容
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Column(
                        children: [
                          const SizedBox(height: 32),
                          Text(
                            '语音起卦',
                            style: Theme.of(context).textTheme.displayLarge,
                          ),
                          const SizedBox(height: 16),
                          Text(
                            '请口述你的困惑，AI将为你提取关键词。',
                            style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                              color: Colors.black.withOpacity(0.7),
                            ),
                          ),
                          const SizedBox(height: 32),
                          
                          // 动画麦克风按钮
                          GestureDetector(
                            onTap: _permissionDenied ? _showPermissionDialog : _toggleListening,
                            child: AnimatedBuilder(
                              animation: _pulseAnimation,
                              builder: (context, child) {
                                return Transform.scale(
                                  scale: _isListening ? _pulseAnimation.value : 1.0,
                                  child: Container(
                                    width: 192,
                                    height: 192,
                                    decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: Colors.white,
                                      boxShadow: [
                                        BoxShadow(
                                          color: _isListening 
                                              ? Colors.blue.withOpacity(0.3)
                                              : Colors.blue.withOpacity(0.2),
                                          blurRadius: _isListening ? 25 : 20,
                                          spreadRadius: _isListening ? 8 : 5,
                                        ),
                                      ],
                                    ),
                                    child: Stack(
                                      alignment: Alignment.center,
                                      children: [
                                        Container(
                                          width: 160,
                                          height: 160,
                                          decoration: BoxDecoration(
                                            shape: BoxShape.circle,
                                            color: Colors.blue.withOpacity(_isListening ? 0.3 : 0.2),
                                          ),
                                        ),
                                        Container(
                                          width: 128,
                                          height: 128,
                                          decoration: BoxDecoration(
                                            shape: BoxShape.circle,
                                            color: Colors.blue.withOpacity(_isListening ? 0.4 : 0.3),
                                          ),
                                        ),
                                        const Text(
                                          '🎤',
                                          style: TextStyle(fontSize: 50),
                                        ),
                                        if (_permissionDenied)
                                          Container(
                                            width: 192,
                                            height: 192,
                                            decoration: BoxDecoration(
                                              shape: BoxShape.circle,
                                              color: Colors.black.withOpacity(0.3),
                                            ),
                                            child: const Center(
                                              child: Icon(
                                                Icons.mic_off,
                                                color: Colors.white,
                                                size: 50,
                                              ),
                                            ),
                                          ),
                                      ],
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                          const SizedBox(height: 16),
                          Text(
                            _permissionDenied
                                ? (_recognizedText.startsWith('设备不支持语音识别功能')
                                    ? '设备不支持语音识别'
                                    : (_recognizedText.startsWith('初始化语音服务失败')
                                        ? '语音服务初始化失败'
                                        : '需要麦克风权限'))
                                : (_isListening ? '正在聆听... (点击停止)' : '点击开始录音'),
                            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                              color: _permissionDenied ? Colors.red : Colors.black,
                            ),
                          ),
                          if (_recognizedText.isNotEmpty) ...[
                            const SizedBox(height: 24),
                            Container(
                              padding: const EdgeInsets.all(16),
                              decoration: BoxDecoration(
                                color: Colors.white.withOpacity(0.8),
                                borderRadius: BorderRadius.circular(12),
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.black.withOpacity(0.05),
                                    blurRadius: 10,
                                    offset: const Offset(0, 3),
                                  ),
                                ],
                              ),
                              constraints: BoxConstraints(
                                maxHeight: MediaQuery.of(context).size.height * 0.2,
                              ),
                              child: SingleChildScrollView(
                                child: Text(
                                  _recognizedText,
                                  style: Theme.of(context).textTheme.bodyMedium,
                                ),
                              ),
                            ),
                          ],
                        ],
                      ),
                      
                      // 底部按钮
                      Column(
                        children: [
                          AppPrimaryButton(
                            text: _permissionDenied
                                ? (_recognizedText.startsWith('设备不支持语音识别功能')
                                    ? '功能不可用'
                                    : (_recognizedText.startsWith('初始化语音服务失败')
                                        ? '重试'
                                        : '去设置'))
                                : (_isListening ? '停止录音' : '开始录音'),
                            onPressed: _permissionDenied ? _showPermissionDialog : _toggleListening,
                          ),
                          const SizedBox(height: 16),
                          AppSecondaryButton(
                            text: '取消',
                            onPressed: () => Navigator.pop(context),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}